package com.example.geta;

import cn.hutool.http.HttpUtil;
import lombok.extern.log4j.Log4j2;

import javax.annotation.PreDestroy;
import java.io.File;
import java.util.concurrent.*;

@Log4j2
public class DownloadUtil {

    ExecutorService executorService = null;

    {

        int i = Runtime.getRuntime().availableProcessors();
        log.info("初始化线程池，当前CPU个数：{},初始化线程:{}", i, i * 50);
        executorService = Executors.newFixedThreadPool(i * 50);

    }

    public void download(String url, File file) {
        Future<?> future = executorService.submit(() -> {
            log.info("开始下载：{},本地地址:{}", url, file.getAbsoluteFile());
            HttpUtil.downloadFile(url, file, 15*1000);
        });
        try {
            future.get(1, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }

    }

    public void time() {
        executorService.execute(() -> {
            log.info("开始计时");
            try {
                for (int i = 0; i < 60; i++) {
                    Thread.sleep(1000);
                    log.info("第" + (i + 1) + "秒");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

    @PreDestroy
    public void destroy(){
        if (executorService != null) {
            executorService.shutdown();
        }
    }
}
